<template>
  <page-header-wrapper :title="false">
    <a-card :bordered="false" :style="{margin:'0 -24px',padding:0}">

      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6">
              <a-form-item label="">
                <a-input :allowClear="true" v-model="formData.title" placeholder="标题"/>
              </a-form-item>
            </a-col>
            <a-col :md="6">
              <a-form-item label="">
                <a-input :allowClear="true" v-model="formData.publisher" placeholder="发布者姓名"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="">
                <a-select :allowClear="true" v-model="formData.status" placeholder="状态" default-value="0">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option value="1">正常</a-select-option>
                  <a-select-option value="2">撤回</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="23" :sm="24">
              <span class="table-page-search-submitButtons" style="float: right;">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-operator" v-action:create>
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="created_at" slot-scope="text, record">
          <template>
            {{ record.created_at | setTime }}
          </template>
        </span>
        <span slot="status" slot-scope="text, record">
          <template>
            {{ record.status === 1 ? '正常' : record.status === 2 ? '撤回' : '' }}
          </template>
        </span>
        <span style="text-align: center;" slot="action" slot-scope="text, record">
          <template>
            <a v-action:edit @click="handleEdit(record,1)">编辑</a>
            <a-divider type="vertical"/>
            <a v-action:info @click="handleEdit(record,2)">详情</a>
            <a-divider v-if="record.status == 1" type="vertical"/>
            <a v-action:recall v-if="record.status == 1" @click="handleChangeStatus(record)">撤回</a>
            <a-divider v-if="record.status == 2" type="vertical"/>
            <a v-action:del v-if="record.status === 2" @click="handleRemove(record)">删除</a>
          </template>
        </span>
      </s-table>
      <!-- 增/查/改 弹出模板 -->
      <CreateActivityForm
        ref="CreateActivityForm"
        v-if="visible"
        :model="mdl"
        :villageList="villageList"
        :visible="visible"
        :loading="confirmLoading"
        @cancel="handleCancel"
        @ok="handleOk"
        :okHidden="okHidden"
        :serveList="serveList"
      />
      <!-- 删除/停用确认窗 -->
      <a-modal
        title="提示"
        :visible="modal.show"
        :okHidden="okHidden"
        :confirm-loading="modal.loading"
        @ok="modal.confirm"
        @cancel="modal.show = false"
      >
        <p>{{ modal.text }}</p>
      </a-modal>
      <!-- <step-by-step-modal ref="modal" @ok="handleOk"/> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { lists, create, info, recall, edit, del } from '@/api/activity'
import CreateActivityForm from './modules/CreateActivityForm.vue'
import {
    villageList
  } from '@/api/common'
const statusMap = {
  0: {
    status: 'default',
    text: '撤回'
  },
  1: {
    status: 'success',
    text: '正常'
  }
}

const columns = [
  {
    title: '发布时间',
    dataIndex: 'created_at',
    align: 'center',
    scopedSlots: { customRender: 'created_at' }
  },
  {
    title: '新闻标题',
    dataIndex: 'title',
    align: 'center'
  },
  {
    title: '发布者',
    dataIndex: 'publisher',
    align: 'center'
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    STable,
    CreateActivityForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      okHidden: false, // 弹窗是否隐藏确认按钮
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      villageList: [],
      // 查询参数
      formData: {
        title: '',
        publisher: '',
        status: '',
        page: 1,
        per_page: 20
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        this.formData['page'] = parameter.pageNo
        this.formData['per_page'] = parameter.pageSize
        const res = await lists(this.formData)
        const result = {
          pageNo: res.current_page,
          totalPage: res.last_page,
          data: res.data,
          pageSize: 10,
          totalCount: res.total
        }
        return Promise.resolve(result)
      },
      modal: {
        show: false,
        text: '',
        loading: false,
        confirm: () => {},
        cancel: () => {}
      },
      serveList: [],
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    },
    setTime (ev) {
      const date = new Date(ev)
      // 转换日期
      const y = date.getFullYear()
      let m = date.getMonth() + 1
      m = m < 10 ? ('0' + m) : m
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      let h = date.getHours()
      h = h < 10 ? ('0' + h) : h
      let M = date.getMinutes()
      M = M < 10 ? ('0' + M) : M
      let s = date.getSeconds()
      s = s < 10 ? ('0' + s) : s
      return y + '-' + m + '-' + d + ' ' + h + ':' + M + ':' + s
    }
  },
  created () {
    this.getVillageList()
  },
  methods: {
    getVillageList () {
      // 获取村庄列表
      villageList().then((res) => {
        this.villageList = res.list
        for (let i = 0; i < this.villageList.length; i++) {
          this.$set(this.villageList[i], 'is', false)
        }
      })
    },
    handleAdd () {
      for (let i = 0; i < this.villageList.length; i++) {
        this.$set(this.villageList[i], 'is', false)
      }
      this.mdl = null
      this.visible = true
    },
    handleEdit (record, type) {
      this.$refs.table.localLoading = true
      info({ id: record.id }).then((res) => {
        this.$refs.table.localLoading = false
        // res.village_ids = res.village_ids.toString()
        this.mdl = res
        this.okHidden = type === 2
        this.visible = true
      }).catch(() => {
        this.$refs.table.localLoading = false
      })
    },
    handleOk () {
      const form = this.$refs.CreateActivityForm.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const success = (res, info) => {
            if (res.is_ok == 'Y') {
              this.handleVisible()
              form.resetFields()
              this.$refs.table.refresh()
              this.$message.info(info)
            }
          }
          const final = () => { this.confirmLoading = false }
          // values.village_ids = values.village_ids.indexOf(',') ? values.village_ids.split(',') : ''
          if (values.id > 0) {
            edit(values)
              .then(res => success(res, '修改成功'))
              .finally(final)
          } else {
            values.type = 1
            create(values)
              .then(res => success(res, '新增成功'))
              .finally(final)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleChangeStatus (record) {
      this.openModal(recall, record, '撤回')
    },
    openModal (method, record, statusText) {
      this.modal = {
        ...this.modal,
        text: `确定${ statusText }该内容吗？`,
        show: true,
        confirm: async () => {
          try {
            this.modal.loading = true
            const res = await method({ type: 1, id: record.id })
            if (res.is_ok == 'Y') {
              this.modal.loading = false
              this.modal.show = false
              this.$refs.table.refresh()
              this.$message.info(`${ statusText }成功`)
            }
          } catch (err) {
            console.warn(err)
            this.modal.loading = false
          }
        }
      }
    },
    handleCancel () {
      this.handleVisible()
      const form = this.$refs.CreateActivityForm.form
      form.resetFields() // 清理表单数据（可不做）
    },
    async handleRemove (record) {
      this.openModal(del, record, '删除')
    },
    handleVisible () {
      this.visible = false
      setTimeout(() => {
        this.okHidden = false
      }, 350)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.formData = {
        type: 1, // 公告类型
        title: '',
        publisher: '',
        status: '',
        page: 1,
        per_page: 20
      }
      this.$refs.table.refresh(true)
    }
  }
}
</script>
